package com.tnovoselec.android.favorites.async;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

import android.util.Log;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.Where;
import com.tnovoselec.android.favorites.entity.EnclosureFavoritesDto;
import com.tnovoselec.android.favorites.entity.NewsFavoritesDto;

/**
 * Title: Android Framework - Favorites <br />
 * Copyright: Copyright (c) 2011 <br />
 * NTH Company: NTH d.o.o. <br />
 * 
 * @author Tomislav Novoselec
 * @version 1.0.0
 * @since 1.0.0
 */

public class GetFavorites implements Callable<List<NewsFavoritesDto>>{
    
    private static String TAG = GetFavorites.class.getSimpleName();
    
    private Dao<NewsFavoritesDto, String> favoritesDao;
    private Dao<EnclosureFavoritesDto, String> enclosureDao = null;
    
    public GetFavorites(Dao<NewsFavoritesDto, String> favoritesDao, Dao<EnclosureFavoritesDto, String> enclosureDao){
	super();
	this.favoritesDao = favoritesDao;
	this.enclosureDao = enclosureDao;
    }

    @Override
    public List<NewsFavoritesDto> call() throws Exception {
	List<NewsFavoritesDto> items = null;
	List<EnclosureFavoritesDto> enclosures = null;
	
	QueryBuilder<EnclosureFavoritesDto, String> queryBuilder = enclosureDao.queryBuilder();
	
	try {
	    items = favoritesDao.queryForAll();
	    for (NewsFavoritesDto news : items){
		PreparedQuery<EnclosureFavoritesDto> query = queryBuilder.prepare();
		queryBuilder.setWhere(getWherePart(queryBuilder, news));
		enclosures = enclosureDao.query(query);
		news.setEnclosures(enclosures);
	    }
	   
	} catch (Exception e) {
	    Log.e(TAG, e.getMessage());
	    return null;
	}
	// TODO Auto-generated method stub
	return items;
    }
    
    private Where<EnclosureFavoritesDto, String> getWherePart(QueryBuilder<EnclosureFavoritesDto, String> builder, NewsFavoritesDto news){
	Where<EnclosureFavoritesDto, String> where = builder.where();
	try {
	    where.idEq(news.getGuid());
	} catch (SQLException e) {
	    // TODO Auto-generated catch block
	    Log.e(TAG, e.getMessage());
	}
	return where;
    }

}
